package com.jinchengll.xigua.dao;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.jinchengll.xigua.XiguaApplication;

/**
 * SharedPreferences提供持久层
 *
 * @author jinchengll
 * @since 2021/10/5
 */
public class SPDao implements IDao {

    @Override
    public <T> T getValue(String key, Class<T> clazz) {
        String valueString = getSharedPreferences().getString(key, null);
        if (valueString == null) return null;
        return (T) new Gson().fromJson(valueString, clazz);
    }

    @Override
    public <T> void saveValue(String key, T value) {
        SharedPreferences.Editor edit = getSharedPreferences().edit();
        edit.putString(key, new Gson().toJson(value));
        edit.apply();
    }

    @Override
    public boolean isSaved(String key) {
        return getSharedPreferences().contains(key);
    }

    /**
     * 清空缓存
     */
    public void clean() {
        SharedPreferences.Editor edit = getSharedPreferences().edit();
        edit.clear().apply();
    }

    private SharedPreferences getSharedPreferences() {
        return XiguaApplication.getContext()
                .getSharedPreferences("xigua_cache", Context.MODE_PRIVATE);
    }
}
